import { types } from "recast";

const { ifStatement, blockStatement, expressionStatement } = types.builders;

/**
 * 获取所有表达式陈述语句，如果该表达式为三元运算符，那么分解为if else语句
 */
const modifyConditionalExpression = function (path) {
  const newStatement = ifStatement(
    path.node.expression.test,
    blockStatement([expressionStatement(path.node.expression.consequent)]),
    blockStatement([expressionStatement(path.node.expression.alternate)])
  );

  const parentPath = path.insertBefore(newStatement);
  path.prune();
  parentPath.each((childPath) => {
    if (newStatement === childPath.node) {
      this.visit(childPath);
    }
  });
};

export default modifyConditionalExpression;
